﻿using Sunny.UI;
using System;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Xml.Linq;

namespace XML翻译工具
{
    public partial class Main_from : UIForm
    {

        private string from { get; set; } = "zh";
        private string to { set; get; } = "en";
        private XDocument xDocument { get; set; } = new XDocument();
        public Main_from()
        {
            InitializeComponent();
        }
        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "选择要翻译的XML文件";
            openFileDialog.Filter = "xml文件 (*.xml)|*.xml";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                uiTextBox_path.Text = openFileDialog.FileName;
            }
            else
            {
                UIMessageTip.ShowWarning("您已经取消操作");
                return;
            }
            xDocument = Classtool.xDocument(uiTextBox_path.Text);
        }

        private void uiSymbolButton_start_Click(object sender, EventArgs e)
        {
            uiProcessBar1.Maximum = xDocument.Descendants("data").Count();
            from = if_lang(uiComboBox1.Text);
            to = if_lang(uiComboBox2.Text); 
            Thread thread = new Thread(start_xml);
            thread.Start();
        }

        private string if_lang(string str)
        {
            switch (str)
            {
                case "中文": return"zh";
                case "英文": return "en";
                default: return "null";
            }
        }
        private void start_xml()
        {
            foreach (var data in xDocument.Descendants("data"))
            {
                var titleElement = data.Element("label");

                if (titleElement != null)
                {
                    string originalTitle = titleElement.Value;
                    string newTitle = Classtool.Main_tool(to, from, originalTitle);
                    titleElement.Value = newTitle;
                    uiProcessBar1.Value++;
                    Thread.Sleep(2000);
                }
            }
            UIMessageBox.ShowSuccess("翻译完毕");
        }

        private void uiSymbolButton_save_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存翻译后的XML文件";
            saveFileDialog.Filter = "xml文件 (*.xml)|*.xml";
            if(saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                xDocument.Save(saveFileDialog.FileName);
                Console.WriteLine(saveFileDialog.FileName);
            }
        }
    }
}
